package com.siyoumi.sh.modules.jm;

import com.siyoumi.sh.modules.common.HandleBase;
import com.siyoumi.sh.modules.common.IHandle;
import com.siyoumi.sh.modules.jm.entity.JmApiToken;
import com.siyoumi.util.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//屈记冰室
@Slf4j
public class WatsonsHandle
        extends HandleBase
        implements IHandle {
    @Override
    public void run() {
        if (getArrToken().size() <= 0) {
            log.error("未配置WATSONS_TOKEN");
            return;
        }
        XLog.info(this.getClass(), "BEGIN:" + XDate.toDateTimeString());

        Map<String, String> arrTask = getArrTask();

        StringBuilder sendMsg = new StringBuilder();
        sendMsg.append("**屈记冰室**\n\n");

        for (Map.Entry<String, String> task : arrTask.entrySet()) {
            String taskName = task.getKey();
            String returnStr = "";
            switch (taskName) {
                case "浏览任务":
                    returnStr = lookHandle(task);
                    break;
                default:
                    break;
            }

            sendMsg.append(returnStr);
        }

        //发信息
        sendMsg(sendMsg.toString());

        XLog.info(this.getClass(), "END:" + XDate.toDateTimeString());
    }

    public Map<String, String> getArrTask() {
        Map<String, String> arr = new HashMap<>();
        arr.put("浏览任务", "");
        return arr;
    }

    /**
     * token格式
     * name|wx_from|wx_from_enc&name2|wx_from2|wx_from_enc2
     */
    protected List<JmApiToken> getArrToken() {
        String token = System.getenv("WATSONS_TOKEN");
        if (XStr.isNullOrEmpty(token)) {
            return new ArrayList<>();
        }

        List<JmApiToken> tokenArr = new ArrayList<>();
        String[] jmTokenArr = token.split("&");
        for (String s : jmTokenArr) {
            String[] dataArr = s.split("\\|");
            tokenArr.add(JmApiToken.getIns(dataArr[0], dataArr[1], dataArr[2]));
        }

        return tokenArr;
    }


    //任务浏览
    @SneakyThrows
    public String lookHandle(Map.Entry<String, String> task) {
        String apiUrlArticleList = "https://sapi.watsons.xiao-bo.net/__api_java__/z_app/user_attr_up/web/get_article_picture_list?page=1&page_size=100&type=article&join_type=" +
                "&site_id=app.watsons&{wx_from}";

        StringBuilder sendMsg = new StringBuilder();
        String taskName = task.getKey();
        logAndSet(sendMsg, "**" + taskName + "** \n\n");

        List<JmApiToken> tokenArr = getArrToken();


        List<String> helpOpenid = getHelpOpenid(tokenArr.get(0));

        for (JmApiToken token : tokenArr) {
            String userName = token.getName();

            String apiUrl = apiUrlArticleList
                    .replace("{wx_from}", token.getWxFromQuery());
            XReturn r = requestApi(apiUrl);
            List<Map<String, Object>> listData = r.getData("list_data");


            Map<String, Object> task0 = null;

            List<Map<String, Object>> listData1 = new ArrayList<>(); //未完成浏览任务
            for (Map<String, Object> taskData : listData) {
                Integer joinType = (Integer) taskData.get("artpic_join_type");
                Integer state = (Integer) taskData.get("attch_state");
                Integer prizeFun = (Integer) taskData.get("artpic_prize_fun");
                if (state != null) {
                    if (1 == state) continue; //已完成
                }

                if (joinType != 1) {
                    if (joinType == 0) {
                        //分享任务，收集一个奖励最高的
                        if (task0 == null) {
                            task0 = taskData;
                        } else {
                            Integer prizeFun0 = (Integer) task0.get("artpic_prize_fun");
                            if (prizeFun0 < prizeFun) {
                                task0 = taskData;
                            }
                        }
                    }
                    //非浏览任务
                } else {
                    //浏览任务
                    listData1.add(taskData);
                    break;
                }
            }
            if (task0 != null) {
                listData1.add(task0);
            }


            if (listData1.size() <= 0) {
                logAndSet(sendMsg, XStr.concat(userName, "-没有可执行的浏览任务", "\n\n"));
            }

            for (Map<String, Object> taskData : listData1) {
                Integer joinType = (Integer) taskData.get("artpic_join_type");
                String artpicId = (String) taskData.get("artpic_id");
                Integer s = (Integer) taskData.get("artpic_wait_time");
                String title = (String) taskData.get("artpic_title");
                String desc = (String) taskData.get("artpic_desc");

                sendMsg.append(XStr.concat(userName, "-", lookTaskType(joinType), "\n\n"));

                JmApiToken tokenHelp = token;
                if (joinType == 0) {
                    logAndSet(sendMsg, "执行助力任务");
                    if (helpOpenid.size() <= 0) {
                        logAndSet(sendMsg, XStr.concat(userName, "-未找到帮助openid", "\n\n"));
                        continue;
                    }

                    tokenHelp = JmApiToken.getIns("助力用户", helpOpenid.get(0), openidEnc(helpOpenid.get(0)));
                    helpOpenid.remove(0);
                } else {
                    logAndSet(sendMsg, "执行浏览任务");
                }

                XReturn rLanuch = lookLanuch("0", artpicId, tokenHelp, token.getWxFrom());
                if (rLanuch.ok()) {
                    logAndSet(sendMsg, XStr.concat(userName, "-发起任务", title, desc, "\n\n"));
                    XApp.sleep(s);
                    logAndSet(sendMsg, XStr.concat(userName, "-停" + s, "秒", "\n\n"), true);

                    XReturn rLanuch1 = lookLanuch("1", artpicId, tokenHelp, token.getWxFrom());
                    logAndSet(sendMsg, XStr.concat(userName, "-", rLanuch1.getErrMsg(), "\n\n"));
                } else {
                    logAndSet(sendMsg, XStr.concat(userName, "-发起任务失败：", rLanuch.getErrMsg(), "\n\n"));
                }
            }
        }

        return sendMsg.toString();
    }

    //任务开始与完成
    private XReturn lookLanuch(String state, String artpicId, JmApiToken token, String masterOpenid) {
        String apiUrlArticleLaunch = "https://sapi.watsons.xiao-bo.net/__api_java__/z_app/user_attr_up/web/launch?" +
                "master_openid={wx_from_0}&artpic_id={artpic_id}&state={state}&site_id=app.watsons&{wx_from}";

        String apiUrlLanuch = apiUrlArticleLaunch
                .replace("{state}", state)
                .replace("{artpic_id}", artpicId)
                .replace("{wx_from_0}", masterOpenid)
                .replace("{wx_from}", token.getWxFromQuery());
        return requestApi(apiUrlLanuch);
    }


    /**
     * 获取帮助的openid
     *
     * @param token
     */
    private List<String> getHelpOpenid(JmApiToken token) {
        String dirPath = "./_txt/watsons/";
        String filePath = dirPath + "redbook.txt";
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdirs();
            XFile.putContent(filePath, "0");
        }

        Integer pageIndex = XStr.toInt(XFile.getContent(filePath), 1);
        pageIndex++;
        String apiUrl = "https://sapi.watsons.xiao-bo.net/z_app/redbook/web/zz_api__api_x_quan__funcList?page_size=2&type=6&site_id=app.watsons"
                + "&page={page}&{wx_from}";
        apiUrl = apiUrl
                .replace("{page}", pageIndex.toString())
                .replace("{wx_from}", token.getWxFromQuery());
        XReturn r = requestApi(apiUrl);

        List<String> openidList = new ArrayList<>();
        if (r.ok()) {
            List<Map> list = r.getData("list");
            for (Map map : list) {
                openidList.add((String) map.get("wxuser_id"));
            }
            XFile.putContent(filePath, pageIndex.toString());
        }


        return openidList;
    }


    /**
     * 获取任务类型
     *
     * @param type
     */
    private String lookTaskType(int type) {
        switch (type) {
            case 0:
                return "浏览任务";
            case 1:
                return "分享任务";
            default:
                return "未知";
        }
    }

    /**
     * enc openid
     *
     * @param openid
     */
    private String openidEnc(String openid) {
        int preLen = 9;
        String base64 = XStr.base64Enc(openid);
        String base64_2 = XStr.base64Enc(base64);

        String pre = XStr.md5(StringUtils.substring(openid, 0, 8)).toLowerCase();
        pre = pre.substring(0, preLen);

        return pre + base64_2;
    }
}
